package com.m3958.firstgwt.server.camel;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.persistence.EntityManager;
import javax.persistence.Query;


import org.apache.camel.Exchange;
import org.apache.camel.Handler;

import com.google.common.io.Files;
import com.google.inject.Inject;
import com.m3958.firstgwt.server.model.Article;
import com.m3958.firstgwt.server.model.Asset;
import com.m3958.firstgwt.server.model.WebHost;
import com.m3958.firstgwt.server.utils.Osdetecter;

public class RewriteMapGenerator {
	
	@Inject
	protected com.google.inject.Provider<EntityManager> emp;
	
	@Handler
	public void generate() throws IOException{
		File f;
		if(Osdetecter.isWindows()){
			f = new File("e:/siteroot/hosttodir.txt");
		}else{
			f = new File("/usr/local/www/siteroots/hosttodir.txt");
		}
		
		String qs = "SELECT h FROM WebHost AS h WHERE h.audit = TRUE";
		Query q = emp.get().createQuery(qs);
		
		List<WebHost> whs = q.getResultList();
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f)));
		
		for(WebHost h : whs){
			String s = h.getName() + " " + h.getWebSite().getId() + "/" + h.getTheme();
			out.println(s);
		}
		out.close();
	}
	
	
	public void assetMigration(Exchange exchange){
		Integer num = exchange.getIn().getBody(Integer.class);
		if(num == null || num == 0){
			num = 1;
		}
		String qs = "SELECT a.id FROM Asset AS a WHERE a.fileId LIKE '%-%'";
		Query q = emp.get().createQuery(qs);
		q.setFirstResult(0);
		q.setMaxResults(num);
		List<Integer> as = q.getResultList();
		exchange.getOut().setBody(as);
	}
	
	public void migrationOneAsset(int body) throws IOException{
		String osname = System.getProperty("os.name");
		File f;
		if(osname.contains("indow")){
			f = new File("e:/abc");
		}else{
			f = new File("/usr/local/www/abc");
		}
		
		EntityManager em = emp.get(); 
		
		em.getTransaction().begin();
		Asset a = em.find(Asset.class, body);
		
		File of = new File(f,a.getFilePath());
		if(!of.exists()){
			em.remove(a);
			em.getTransaction().commit();
			em.close();
			return;
		}
		
		a.setFileId(a.getId() + "");
		String[] sss = (a.getId() + "").split("");
		int l = sss.length;
		String s = sss[l-3] + "/" + sss[l-2] + "/" + sss[l-1] + "/";
		String ext = a.getExtension();
		if(ext == null || ext.isEmpty()){
			String[] ee = a.getOriginName().split("\\.");
			if(ee.length > 0){
				ext = ee[ee.length - 1];
				a.setExtension("." + ext);
			}
		}
		a.setFilePath(s + a.getId() + a.getExtension());
		
		File dd = new File(f,s);
		File nf = new File(f,a.getFilePath());
		if(!dd.exists()){
			Files.createParentDirs(nf);
		}
		
		
		Files.copy(of, nf);
		em.merge(a);
		
		em.getTransaction().commit();
		em.close();
	}
	
	public void articleAsset(){
		EntityManager em = emp.get(); 
		em.getTransaction().begin();
		
		String qs = "SELECT a FROM Article AS a";
		Query q = em.createQuery(qs);
		
		List<Article> articles = q.getResultList();
		Pattern p = Pattern.compile("\"/asset/(\\d+)\\?.*?\"", Pattern.MULTILINE|Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
		Pattern p1 = Pattern.compile("\"/asset/(\\d+)\"", Pattern.MULTILINE|Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
		for(Article ar:articles){
			String content = ar.getContent();
			Matcher m = p.matcher(content);
			if(m.find()){
				try {
					String aid = m.group(1);
					int iid = Integer.parseInt(aid);
					Asset a = em.find(Asset.class, iid);
					if(a == null)continue;
					content = m.replaceFirst("\"/asset/$1" + a.getExtension() + "\"");
					ar.setContent(content);
					em.merge(ar);
					System.out.println("matched");
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}
			
			Matcher m1 = p1.matcher(content);
			if(m1.find()){
				try {
					String aid = m1.group(1);
					int iid = Integer.parseInt(aid);
					Asset a = em.find(Asset.class, iid);
					if(a == null)continue;
					content = m1.replaceFirst("\"/asset/$1" + a.getExtension() + "\"");
					ar.setContent(content);
					em.merge(ar);
					System.out.println("matched");
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		em.getTransaction().commit();
		em.close();
	}
}
